﻿using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using up7.db.biz;
using up7.db.model;
using up7.db.utils;
using up7.db.database;
using up7.filemgr.app;
using up7.db.database.up7.sql;
using Newtonsoft.Json.Linq;

namespace up7.db
{
    /// <summary>
    /// 为了解决100W+的文件夹存储，此页面仅记录文件夹基本信息
    /// 文件夹文件和层级结构在f_post.aspx页面提供。
    /// </summary>
    public partial class fd_create : WebBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string id = this.reqStr("id");
            string pathLoc = this.reqStrDecode("pathLoc");
            string sizeLoc = this.reqStr("sizeLoc");
            string callback = this.reqStr("callback");
            long lenLoc = this.reqLong("lenLoc");
            string uid = this.reqStr("uid");

            FileInf f          = new FileInf();
            f.nameLoc          = Path.GetFileName(pathLoc);
            f.nameSvr          = f.nameLoc;
            f.id               = id;
            f.pathLoc          = pathLoc;
            f.sizeLoc          = sizeLoc;
            f.lenLoc           = lenLoc;
            f.fdTask           = true;
            f.uid              = uid;

            //生成路径，格式：upload/年/月/日/guid/文件夹名称
            PathGuidBuilder pb = new PathGuidBuilder();
            f.pathSvr          =  pb.genFolder(f);
            f.pathSvr          = f.pathSvr.Replace("\\", "/");
            if (!PathTool.mkdir(f.pathSvr))
            {
                this.toContent("create dir error", 500);
                return;
            }

            //创建层级信息文件
            FolderSchema fs = new FolderSchema();
            if (!fs.create(f))
            {
                this.toContent("create schema file error", 500);
                return;
            }

            //添加到数据表
            SqlFile.build().Add(f);

            //触发事件
            up7_biz_event.folder_create(f);

            string json = JsonConvert.SerializeObject(f);
            json = HttpUtility.UrlEncode(json);
            json = json.Replace("+", "%20");
            var jo = new JObject { { "value", json } };
            json = callback + string.Format("({0})", JsonConvert.SerializeObject(jo));
            this.toContentJson(json);
        }
    }
}